package gen.tools.init;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class DataSourceFactory implements ServletContextListener {
	
	//所有不同目標系統連線的 DataSource
	//private Map<Integer,ComboPooledDataSource> dataSourceMap = null;

	public DataSourceFactory() {/*
		dataSourceMap = new HashMap<Integer,ComboPooledDataSource>();
	*/}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {/*
		
		String res = "Start to perform contextDestroyed...";
		
		//將所有已建立的DataSource移除
		Iterator<Entry<Integer, ComboPooledDataSource>> iter = dataSourceMap.entrySet().iterator();
		
		while (iter.hasNext()) {
			Map.Entry<Integer, ComboPooledDataSource> dataSourceEntry = (Map.Entry<Integer, ComboPooledDataSource>) iter.next();
			res += "\nclosing connection to target system:\t"+dataSourceEntry.getKey()+" ....";
			dataSourceEntry.getValue().close();
			res += "done";
		}
		System.out.println(res);
	*/}

	public void contextInitialized(ServletContextEvent servletContextEvent) {/*
		//建立所有目標系統的DataSource
		
		ServletContext ctx = servletContextEvent.getServletContext();
		String res = "Start to perform contextInitialized...";
		res += "\nContextPath:\t"+ctx.getContextPath();
		res += "\nRealPath:\t"+ctx.getRealPath("/");
		
		Widgets wid = new Widgets();
		Connection conn = null;
		
		//找尋所有目標系統
		String sql = "SELECT t1.tarSysSN,t2.ip,t2.port,t2.id,t2.pwd,t2.dbName,t3.strProtocol FROM mpsysdb t1,dblogin t2,dbtype t3 WHERE t2.DBTypeSN=t3.DBTypeSN AND t1.dbLoginSN=t2.dbLoginSN AND t1.tarSysSN !=?";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			int localSystemId = wid.getLocalSysemId();
			conn = wid.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, localSystemId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				int targetSystemId = rs.getInt("tarSysSN");
				
				res += "\nconstructing connection to target system:\t"+targetSystemId+" ....";
				
				String jdbcUrl = rs.getString("strProtocol")+"://"+rs.getString("ip")+":"+rs.getInt("port")+"/"+rs.getString("dbName");
				
				ComboPooledDataSource cpds = new ComboPooledDataSource();
				cpds.setDriverClass("com.mysql.jdbc.Driver");
		    	cpds.setJdbcUrl( jdbcUrl );
		    	cpds.setUser( rs.getString("id") );
		    	cpds.setPassword( rs.getString("pwd") );
		    	cpds.setMinPoolSize(3);
		    	cpds.setMaxPoolSize(5);
				
		    	dataSourceMap.put(targetSystemId, cpds);
		    	res += "done";
			}
			System.out.println(res);
	        ctx.setAttribute("dataSourceMap", dataSourceMap);
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) { e.printStackTrace(); }
		}
	*/}

}
